/**
 * 
 */
package com.iexbuy.ihg.net;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;

import com.baidu.navisdk.util.common.StringUtils;
import com.iexbuy.ihg.App;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.entity.Response;
import com.iexbuy.ihg.entity.UserObject;
import com.iexbuy.ihg.entity.UserObjectResponse;
import com.iexbuy.ihg.ui.activity.MainTabActivity;
import com.iexbuy.ihg.ui.activity.StartActivity;
import com.iexbuy.ihg.ui.fragment.LoginFragment;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.ToastUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.apache.http.entity.StringEntity;

/**
 * @author ban
 *
 */
public class ServiceHelper {

	public static final String SERVER_ROOT = "http://ibuy.ci.passion-info.com/ibuy/rest/";
//	public static final String SERVER_ROOT = "http://112.74.113.67/rest/";

	public static final String SERVER_ADDRESS = SERVER_ROOT;
	
	public static final String LOGIN = SERVER_ADDRESS + "login.html";
	public static final String GET_VERIFYCODE = SERVER_ADDRESS + "getVerifyCode.html";
	public static final String GET_APK_LAST_VERSION = SERVER_ADDRESS + "getAppLastVersion.do";
	public static final String CHECK_VERIFY_CODE = SERVER_ADDRESS + "checkVerifyCode.html";
	public static final String REGISTER_WITH_PASSWORD = SERVER_ADDRESS + "submitPassword.html";
	public static final String GET_ADS_BANNERS = SERVER_ADDRESS + "getAdsBanners.html";
	public static final String GET_NEAR_SHOPS = SERVER_ADDRESS + "getNearShops.html";
	public static final String GET_YUN_GUO_READY_OPEN_ITEMS = SERVER_ADDRESS + "getReadyOpenItems.html";
	public static final String GET_BUSINESS_HOT_TYPE = SERVER_ADDRESS + "getBusinessType.html";
	public static final String GET_TOP_SHOP_CENTERS = SERVER_ADDRESS + "getTop3ShopCenters.html";
	public static final String GET_SHOP_CENTERS = SERVER_ADDRESS + "getShopCenters.html";
	public static final String GET_SHOP_CENTER_CATEGORYS = SERVER_ADDRESS + "getShopCenterCategorys.html";
	public static final String GET_SHOP_CENTERS_DETAIL = SERVER_ADDRESS + "getShopCenterDetail.html";
	public static final String GET_SHOPLIST_BY_SHOP_CENTERS_ID = SERVER_ADDRESS + "getShopListByShopCenterId.html";


	public static final String GET_SHOP_DETAIL = SERVER_ADDRESS + "getShopDetail.html";
	public static final String GET_GOODS_DETAIL = SERVER_ADDRESS + "getGoodsDetail.html";
	public static final String SUBMIT_DEAL = SERVER_ADDRESS + "submitDeal.html";
	public static final String PAY_BY_CASH = SERVER_ADDRESS + "payByCash.html";
	public static final String ALIYPAY_NOTIFY = SERVER_ADDRESS + "alipayNotify.html";
	public static final String GET_DEFAULT_SHOP_PRODUCTS = SERVER_ADDRESS + "getDefaultShopProducts.html";
	public static final String GET_PRODUCT_CATOGERY = SERVER_ADDRESS + "getGoodsTypeList.html";
	public static final String GET_LASH_LUCK_USERS = SERVER_ADDRESS + "getLastLuckUsers.html";
	public static final String GET_READY_OPEN_ITEMS = SERVER_ADDRESS + "getReadyOpenItems.html";
	public static final String GET_LUCK_ITEM_BY_ID = SERVER_ADDRESS + "getLuckItemById.html";
	public static final String GET_LUCK_ITEM_BY_ID_AND_PEROID = SERVER_ADDRESS + "getLuckItemByIdAndPeroid.html";
	public static final String GET_CHOU_JIAN_RECORDS = SERVER_ADDRESS + "getChouJiangRecords.html";
	public static final String GET_CHOU_JIANG_ITEM_DETAIL = SERVER_ADDRESS + "getChouJiangItemDetail.html";
	public static final String GET_JIUAN_RESULT = SERVER_ADDRESS + "getJiuanResult.html";
	public static final String SUBMIT_YUN_GUO_DEAL = SERVER_ADDRESS + "submitYunGouDeal.html";
	public static final String SUBMIT_HUO_GUO_JI_SHUAN_RULE = SERVER_ADDRESS + "getHuanGouJiSuanRule.html";
	public static final String GET_MY_MIAN_DAN_PRODILE = SERVER_ADDRESS + "getMyLingQianProfile.html";
	public static final String GET_LING_QIANG_RULE = SERVER_ADDRESS + "getLingQianRule.html";
	public static final String SUBMIT_LING_QIANG = SERVER_ADDRESS + "submitToLingQian.html";
	public static final String GET_LING_QIANG_MY_RECORDS = SERVER_ADDRESS + "getLingQianMyRecords.html";
	public static final String GET_LING_QIAN_LASTEST_RECORDS = SERVER_ADDRESS + "getLingQianLatestRecords.html";
	public static final String GET_LING_QIANG_SUMMARY = SERVER_ADDRESS + "getLingQianSummary.html";
	public static final String GET_MY_PROFILE = SERVER_ADDRESS + "getMyProfile.html";
	public static final String GET_MY_DEALS = SERVER_ADDRESS + "getMyDeals.html";
	public static final String GET_MY_COUPONS = SERVER_ADDRESS + "getMyCoupons.html";
	public static final String GET_MY_GOLD_COIN_RECORDS = SERVER_ADDRESS + "getMyGoldCoinRecords.html";
	public static final String GET_MY_CASH_RECORDS = SERVER_ADDRESS + "getMyCashRecords.html";
	public static final String GET_DEAL_HISTORY_DETAIL = SERVER_ADDRESS + "getDealHistoryDetail.html";
	public static final String GET_MY_COLD_COIN_RECORDS = SERVER_ADDRESS + "getMyGoldCoinRecords.html";
	public static final String SUBMIT_USER_NAME = SERVER_ADDRESS + "submitUserName.html";
	public static final String GET_CHOU_JIAN_LUCK_HISTORY = SERVER_ADDRESS + "getChouJiangLuckHistory.html";
	public static final String GET_COMMENT_PRODUCT_LIST = SERVER_ADDRESS + "getCommentList.html";
	public static final String GET_MY_ADDRESS = SERVER_ADDRESS + "getMyAddress.html";
	public static final String SUBMIT_ADDRESS = SERVER_ADDRESS + "saveAddress.html";
	public static final String GET_COMMENT_LIST = SERVER_ADDRESS + "getCommentList.html";
	public static final String ADD_COMMENT_LIST = SERVER_ADDRESS + "addCommentList.html";
	public static final String GET_COMMON_QUESTION_LIST = SERVER_ADDRESS + "getCommonQuestionList.html";
	public static final String SUBIT_INVITOR_MOBILE = SERVER_ADDRESS + "submitInvitorMobile.html";
	public static final String GET_HOT_SEARCH = SERVER_ADDRESS + "getHotSearch.html";
	public static final String SEARCH_SHOP = SERVER_ADDRESS + "searchShop.html";
	public static final String GET_DISTRICT_BY_CITY_CODE = SERVER_ADDRESS + "getDistrictByCityCode.html";
	public static final String GET_CITYS = SERVER_ADDRESS + "getCities.html";
	public static final String GET_ADS_DETAIL = SERVER_ADDRESS + "getAdsDetail.html";
	public static final String SUBMIT_GOLD_PAYMENT = SERVER_ADDRESS + "goldPayment.html";
	public static final String GET_JI_SUAN_RESULT = SERVER_ADDRESS + "getJiuanResult.html";
	public static final String GET_CASH_HISTORY = SERVER_ADDRESS + "getCashHistory.html";
	public static final String SUBMIT_CASH_TIXIANG = SERVER_ADDRESS + "submitCashTiXi.html";
	public static final String GET_CASH_TIXIANG_HISTORY = SERVER_ADDRESS + "getCashTiXiHistory.html";
	public static final String GET_CASH_TIXIANG_HISTORY_DETAIL = SERVER_ADDRESS + "getCashTiXiHistoryDetail.html";
	public static final String GET_COIN_HISTORY = SERVER_ADDRESS + "getCoinHistory.html";
	public static final String GET_COIN_HISTORY_DETAIL = SERVER_ADDRESS + "getCoinHistoryDetail.html";
	public static final String SUBMIT_GOLD_COIN_BUY_ORDER = SERVER_ADDRESS + "recharge.html";
	public static final String GET_CHOU_JIAN_HISTORY = SERVER_ADDRESS + "getChouJiangHistory.html";
	public static final String GET_CHOU_JIAN_HISTORY_By_ITEMID_PERIOD = SERVER_ADDRESS + "getChouJiangHistoryByItemIdAndPeriod.html";
	public static final String SUBMIT_ORDER_COMMENT = SERVER_ADDRESS + "submitOrderComment.html";
	public static final String GET_ORDER_COMMENT = SERVER_ADDRESS + "getOrderComment.html";
	public static final String WX_PREPAY = SERVER_ADDRESS + "wxPrepay.html";
	public static final String GET_USER_HEADER_IMG = SERVER_ADDRESS + "getHeaderImage.html";
	public static final String GET_ABOUT = SERVER_ADDRESS + "getAbout.html";
	public static final String CANCEL_ORDER = SERVER_ADDRESS + "cancelOrder.html";
	public static final String GET_COINSUM = SERVER_ADDRESS + "getCoinSum.html";



	
	public static void send(final Context context, final String uri, final HashMap<String, String> paramMap, final RequestCallBack<String> callBack) {
		if (App.test) {//return test data
			ResponseInfo<String> responseInfo = new ResponseInfo<String>(null, uri, false);
			responseInfo.result = prepareTestData(uri);
			callBack.onSuccess(responseInfo);
			return;
		}
		
		//add the common param
		if (paramMap != null) {
			if(!paramMap.containsKey("token")) paramMap.put("token", App.sPreferences.getToken());
			if(!paramMap.containsKey("devicecode")) paramMap.put("devicecode", App.deviceIdString);
		}
		
		RequestParams params = new RequestParams();
//		try {
			String jsonStr = JsonUtils.ObjectToJson(paramMap);
			Log.i("", "ServiceHelper send:" + uri + ", param:" + jsonStr);
//			params.setBodyEntity(new StringEntity(jsonStr, "utf-8"));
			for (String key : paramMap.keySet()) {
				params.addBodyParameter(key, paramMap.get(key));
//				params.addQueryStringParameter(key, paramMap.get(key));
			}
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
		//start request
        App.http.configCurrentHttpCacheExpiry(1000 * 10);
        App.http.send(HttpRequest.HttpMethod.POST, uri, params,
        		new RequestCallBack<String>() {
    		@Override
        	public void onStart() {
    			callBack.onStart();
            }
    		@Override
    		public void onCancelled() {
    			callBack.onCancelled();
    	    }
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Log.i("", "ServiceHelper response:" + responseInfo.result);
				try {
					Response response = JsonUtils.parseJsonStrToObject(responseInfo.result, Response.class);
					if (response.getHead() != null && response.getHead().getResult() == 1 && response.getHead().getMessage().contains("需要登录")) {//如果过期，自动登录
						handleSessionExpire(context, uri, paramMap, callBack);
					} else if (response.getResultCode() > 0) {
						callBack.onFailure(new HttpException(response.getResultCode()), response.getResultMessage());
					} else {
						callBack.onSuccess(responseInfo);
					}
				} catch (Exception e) {
					e.printStackTrace();
//					CommUtil.showAlert(context, "请求结果处理错误", "请求结果处理错误：" + e.getMessage(), null);
				}
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				Log.i("", "ServiceHelper false:" + error + "-" + msg);
				if (msg.contains("org.apache.http.conn.ConnectTimeoutException")) {
					CommUtil.showAlert(context, "", "连接服务器超时，是否重新请求?", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							ServiceHelper.send(context, uri, paramMap, callBack);
						}
					});
				}
				callBack.onFailure(error, msg);
			}
        });
	}

	private static void handleSessionExpire(Context context, final String uri, final HashMap<String, String> paramMap, final RequestCallBack<String> callBack) {
		if (StringUtils.isNotEmpty(App.sPreferences.getUserName()) && StringUtils.isNotEmpty(App.sPreferences.getPsw())) {
			reLogin(context, App.sPreferences.getUserName(), App.sPreferences.getPsw(), uri, paramMap, callBack);
		} else {
			ToastUtils.toast(context, "请先登录");
			LoginFragment.setIsLoginForbusiness(true);
			CommUtil.openSingleFragmentActivity(context, LoginFragment.class);
		}
	}
	
	
	private static String getUrlParameter(String urlParameterStr, String parameterName) {
		String parameterValue = "";
		String[] parameterArray = urlParameterStr.split("&");
		for (String paramString : parameterArray) {
			if (paramString.startsWith(parameterName)) {
				parameterValue = paramString.split("=").length > 1 ? paramString.split("=")[1] : "";
			}
		}
		return parameterValue;
	}
	
	private static String getRealUrl(String orgUrl) {
		String realUrl = "";
		try {
			URL url = new URL(orgUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.getResponseCode();
			realUrl = conn.getURL().toString();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return realUrl;
	}
	
	private static String prepareTestData(String uri) {
		String responseString = "";
		
		return responseString;
	}


	private static void reLogin(final Context context, final String username, final String passwordMd5, final String uri, final HashMap<String, String> paramMap, final RequestCallBack<String> callBack) {
		final HashMap<String, String> paramMapLogin = new HashMap<String, String>();
		paramMapLogin.put("username", username);
		paramMapLogin.put("pwd", passwordMd5);

		ServiceHelper.send(context, ServiceHelper.LOGIN, paramMapLogin,
			new RequestCallBack<String>() {
				@Override
				public void onStart() {
				}

				@Override
				public void onCancelled() {
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					String responseString = responseInfo.result;
					Log.i("", responseString);
					UserObjectResponse userInfo = JsonUtils.parseJsonStrToObject(responseString, UserObjectResponse.class);
					if (userInfo.getResultCode() == 0) {
						App.sPreferences.setUserName(username);
						App.sPreferences.setName(userInfo.getBody().getName());
						App.sPreferences.setPsw(passwordMd5);
						App.sPreferences.setUserId(userInfo.getBody().getId());
						App.sPreferences.setLoginIn(true);

						ServiceHelper.send(context, uri, paramMap, callBack);//登录成功后重新再发请求
					} else {
						ToastUtils.toast(context, userInfo.getResultMessage());
						LoginFragment.setIsLoginForbusiness(true);
						CommUtil.openSingleFragmentActivity(context, LoginFragment.class);
					}
				}

				@Override
				public void onFailure(HttpException error, String msg) {
					CommUtil.showAlert(context, "登录失败", "用户名或密码不对", null);
				}
			});
	}
}
